package xyz.jiang.common.utils;

import cn.hutool.core.util.StrUtil;
import org.springframework.util.ObjectUtils;
import xyz.jiang.common.mapper.UsersMapper;
import xyz.jiang.common.pojo.entity.Users;

import static xyz.jiang.common.constants.SystemConstants.SYSTEM_CACHE;
import static xyz.jiang.common.constants.UserConstants.USER_CACHE;

public class UserHolder {

    private static final ThreadLocal<String> userThreadLocal = new ThreadLocal<>();

    public static String getUserId() {
        return userThreadLocal.get();
    }

    public static void setUserId(String token) {
        userThreadLocal.set(token);
    }

    public static void removeUserId() {
        userThreadLocal.remove();
    }

    public static Users getCurrentUser() {
        if (StrUtil.isBlank(getUserId())) {
            return null;
        }
        Users user = (Users)RedisUtils.get(SYSTEM_CACHE + USER_CACHE + getUserId());
        if (ObjectUtils.isEmpty(user)) {
            UsersMapper userMapper = SpringContextUtils.getBean(UsersMapper.class);
            user = userMapper.selectById(getUserId());
            if (ObjectUtils.isEmpty(user)) {
                RedisUtils.set(SYSTEM_CACHE + USER_CACHE + getUserId(), user);
            }
        }
        return user;
    }
}
